#!/usr/bin/env python3
"""
JSON语法高亮器
支持JSON文件的高亮显示
"""

from PyQt5.QtCore import QRegExp
from PyQt5.QtGui import QSyntaxHighlighter, QTextCharFormat, QColor

class JSONHighlighter(QSyntaxHighlighter):
    """JSON语法高亮器"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.highlighting_rules = []
        
        # 关键字格式
        keyword_format = QTextCharFormat()
        keyword_format.setForeground(QColor(0, 0, 255))  # 蓝色
        keyword_format.setFontWeight(75)
        
        # 字符串格式
        string_format = QTextCharFormat()
        string_format.setForeground(QColor(163, 21, 21))  # 深红色
        
        # 数字格式
        number_format = QTextCharFormat()
        number_format.setForeground(QColor(9, 134, 88))  # 绿色
        
        # 布尔值格式
        boolean_format = QTextCharFormat()
        boolean_format.setForeground(QColor(128, 0, 128))  # 紫色
        boolean_format.setFontWeight(75)
        
        # null值格式
        null_format = QTextCharFormat()
        null_format.setForeground(QColor(128, 128, 0))  # 橄榄色
        null_format.setFontWeight(75)
        
        # 标点符号格式
        punctuation_format = QTextCharFormat()
        punctuation_format.setForeground(QColor(0, 0, 0))  # 黑色
        punctuation_format.setFontWeight(75)
        
        # 添加规则
        
        # 布尔值
        rule = (QRegExp(r'\btrue\b'), boolean_format)
        self.highlighting_rules.append(rule)
        rule = (QRegExp(r'\bfalse\b'), boolean_format)
        self.highlighting_rules.append(rule)
        
        # null值
        rule = (QRegExp(r'\bnull\b'), null_format)
        self.highlighting_rules.append(rule)
        
        # 数字
        rule = (QRegExp(r'\b\d+\.?\d*\b'), number_format)
        self.highlighting_rules.append(rule)
        
        # 双引号字符串
        rule = (QRegExp(r'".*?"'), string_format)
        self.highlighting_rules.append(rule)
        
        # 标点符号
        punctuation_chars = [r'\{', r'\}', r'\[', r'\]', r':', r',']
        for char in punctuation_chars:
            pattern = QRegExp(char)
            rule = (pattern, punctuation_format)
            self.highlighting_rules.append(rule)
    
    def highlightBlock(self, text):
        """高亮文本块"""
        # 应用单行规则
        for pattern, format in self.highlighting_rules:
            expression = QRegExp(pattern)
            index = expression.indexIn(text)
            while index >= 0:
                length = expression.matchedLength()
                self.setFormat(index, length, format)
                index = expression.indexIn(text, index + length)